package cn.fz.ssedemo.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class RedisMessageSubscriber implements MessageListener {
    @Resource
    private SseEmitterService sseEmitterService;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("redis订阅消息 : {}", message.toString());
        JSONObject jsonObj = JSONUtil.parseObj(message.toString());
        String userId = jsonObj.getInt("createdId").toString();
        // 调用发送代码
        sseEmitterService.sendToUser(userId, jsonObj.toString());
    }

    /*
    前端代码
    * const eventSource = new EventSource('http://your-api.com/sse/subscribe');

eventSource.onopen = function () {
    console.log('Connected to SSE');
};

eventSource.onerror = function (err) {
    console.error('SSE error:', err);
};

eventSource.onmessage = function (event) {
    const alarm = JSON.parse(event.data);
    console.log('Received alarm:', alarm);
    // 在页面上展示报警信息
    displayAlarmNotification(alarm);
};
    * */
}
